package com.pt5.pthouduan.config;

import com.pt5.pthouduan.entity.StatsRecorder;
import com.pt5.pthouduan.entity.TrackerInitializer;
import com.pt5.pthouduan.entity.TrackeredTorrentWithStats;
import com.pt5.pthouduan.service.impl.updatePeerStatsService;
import com.turn.ttorrent.tracker.TorrentsRepository;
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;

import javax.sql.DataSource;

@Configuration
public class TrackerConfig {

    @Value("${tracker.port:6969}")
    private int trackerPort;

    @Value("${tracker.accept.foreign:false}")
    private boolean acceptForeignTorrents;

    @Autowired
    private DataSource dataSource;
    @Autowired
    private TrackerInitializer trackerInitializer;
    @Autowired
    private updatePeerStatsService statsService;

    @Bean
    public Tracker tracker() throws IOException {
        // 1. 创建 Tracker 实例
        //Tracker tracker = new Tracker(6969);
        //Tracker tracker = new Tracker(6969,"127.0.0.1");
        Tracker tracker = trackerInitializer.createTracker();
        // 4. 启动 Tracker（true 表示作为守护线程运行）
        tracker.start(true);

        // 2. 自动加载目录下的所有种子文件
        File torrentsDirectory = new File("D:\\torrenttest\\111111");
        if (torrentsDirectory.exists() && torrentsDirectory.isDirectory()) {
            FilenameFilter filter = (dir, name) -> name.endsWith(".torrent");

            for (File torrentFile : torrentsDirectory.listFiles(filter)) {
                try {
                    TrackedTorrent baseTorrent = TrackedTorrent.load(torrentFile);
                    //获取HashInfo
                    byte[] infoHash = baseTorrent.getInfoHash();
                    System.out.println("Registered torrent hash: " + infoHash);
                    System.out.println("Registered torrent hash: " + baseTorrent.getHexInfoHash());
                    TrackeredTorrentWithStats trackedTorrentWithStats = new TrackeredTorrentWithStats(infoHash,dataSource,"",statsService);
                    tracker.announce(trackedTorrentWithStats);
                    //tracker.announce(TrackedTorrent.load(torrentFile));
                    System.out.println("Registered torrent: " + torrentFile.getName());
                } catch (IOException e) {
                    System.err.println("Failed to load torrent: " + torrentFile.getName());
                    e.printStackTrace();
                }
            }
        }

        // 3. 设置是否接受未知种子
        tracker.setAcceptForeignTorrents(true);



        System.out.println("Tracker started on port " + trackerPort +
                ", accepting foreign torrents: " + acceptForeignTorrents);

        // 添加JVM关闭钩子确保Tracker正常停止
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            tracker.stop();
            System.out.println("Tracker stopped gracefully");
        }));

        System.out.println("All registered torrents:");
        for (TrackedTorrent t : tracker.getTrackedTorrents()) {
            System.out.println(t.getHexInfoHash());
        }


        return tracker;
    }

}